<script setup lang="ts">

import { ref } from 'vue'
import { HubConnectionBuilder } from '@microsoft/signalr'


let list = ref([] as string[])
let msg = ref('')

// 拿到当前登录用户
const username = location.search.split('&')[0].split('=')[1]
// 拿到当前的分组
const groupName = location.search.split('&')[1].split('=')[1]
// 创建连接
const connection = new HubConnectionBuilder()
  .withUrl('/hubs/chatHub')
  .build()

// 监听接收消息
connection.on("messageReceived", (username, message) => {
  // 展示消息
  list.value.push(`${username}: ${message}`)
})

// 开始监听
connection.start()
  .then(() => {
    // 连接成功后，将连接加入到指定的组
    connection.send('joinGroup', groupName)
  })
  .catch(err => alert(err))

const sendMsg = () => {
  // 发送消息（所属组，用户，消息）
  connection.send("newMessage", groupName, username, msg.value)
}



</script>

<template>
  <input type="text" v-model="msg" /> <button @click="sendMsg">发送</button>
  <ul>
    <li>
      <span style="font-weight: bold;">各位分</span>
    </li>
    <li v-for="(item, index) in list" :key="index">
      <span style="font-weight: bold;">{{ item }}: </span>
    </li>
  </ul>
</template>

<style scoped>
h1 {
  font-weight: 500;
  font-size: 2.6rem;
  top: -10px;
}

h3 {
  font-size: 1.2rem;
}

.greetings h1,
.greetings h3 {
  text-align: center;
}

@media (min-width: 1024px) {

  .greetings h1,
  .greetings h3 {
    text-align: left;
  }
}
</style>
